package com.zkingsoft.actions.admin;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.zkingsoft.anotations.SaveRequestToken;
import com.zkingsoft.constance.Dictionary;
import com.zkingsoft.constance.SystemConstance;
import com.zkingsoft.dao.WorkLogDao;
import com.zkingsoft.dingding.user.User;
import com.zkingsoft.model.Article;
import com.zkingsoft.model.Project;
import com.zkingsoft.model.Users;
import com.zkingsoft.model.WorkLog;
import com.zkingsoft.plugin.pojo.PaginationVO;
import com.zkingsoft.plugin.util.LogUtil;
import com.zkingsoft.plugin.util.WebUtil;
import com.zkingsoft.pojo.AjaxResult;
import com.zkingsoft.services.ProjectService;
import com.zkingsoft.services.UsersService;
import com.zkingsoft.services.WorkLogService;
import com.zkingsoft.thread.SendWorkLogThread;

/**
 * @description 个人工作日志
 * @author 吴建
 * @email 1582406829@qq.com
 * @date 2018-07-20
 */
@Controller
@RequestMapping(value = "/admin/WorkLogAction")
public class WorkLogAction {
	@Autowired
	private WorkLogService workLogService;
	
	@Autowired 
	private WorkLogDao workLogDao;
	
	@Resource
	private UsersService usersService;
	
	@Resource
	private ProjectService projectService;
	
	
	/**
	 * 我的日志列表查询
	 * @author 吴建
	 * @email 1582406829@qq.com
	 * @date 2018-07-20
	 * */						
	@RequestMapping(value = "/selectWorkLogList")
	public @ResponseBody AjaxResult selectWorkLogList(WorkLog workLog,PaginationVO pageVo){
		Long id = getMe().getId();
		workLog.setSenderId(id);
		if (pageVo == null) {
			pageVo = new PaginationVO();
		}
		pageVo.setOrder("desc");
		pageVo.setSort("createTime");
		List<WorkLog> w =workLogService.selectWorkLogList(workLog,pageVo);
		LogUtil.info("进入日志列表",null);
		return new AjaxResult(AjaxResult.STATUS_OK, null, null,w,workLogService.selectWorkLogListTotal(workLog));
	}
	
	/**
	 * 我的日志列表查询
	 * @author 吴建
	 * @email 1582406829@qq.com
	 * @date 2018-07-20
	 * */						
	@RequestMapping(value = "/selectWorkLogList1")
	public @ResponseBody AjaxResult selectWorkLogList1(WorkLog workLog,PaginationVO pageVo){
		Long id = getMe().getId();
		workLog.setUserId(id.toString());
		if (pageVo == null) {
			pageVo = new PaginationVO();
		}
		if(workLog.getSendID()!=null && workLog.getSendID()!=""){
			long userId=Long.parseLong(workLog.getSendID());
			workLog.setSenderId(userId);
		}
		pageVo.setOrder("desc");
		pageVo.setSort("createTime");
		List<WorkLog> work =workLogService.selectWorkLogList(workLog,pageVo);
//		校验查出来的是否有不包含接受者的的用户
		for(int i=0;i<work.size();i++){
			//截取所抄送的人
			String[] str =work.get(i).getReceiverId().split(",");
			boolean flg = false;
			//遍历寻找集合中是否有不是本Id数据的存在
			for(int j=0;j<str.length;j++) {
				if(str[j].equals(id.toString())){
					flg=true;
					continue;
				}
			}
			//删除
			if(!flg){
				work.remove(i);
			}
		}
		LogUtil.info("进入日志列表",null);
		return new AjaxResult(AjaxResult.STATUS_OK, null, null,work,workLogService.selectWorkLogListTotal(workLog));
	}
	
	/**
	 * 获取登录员工登录对象
	 * @author 姜友瑶
	 * @date 2016/7/5
	 */
	public Users getMe() {
		return (Users) ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getSession().getAttribute(SystemConstance.LOGIN_KEY);	
	}
	
	/**
	 * 进入修改页面
	 * @author 吴建
	 * @date 2018/7/23
	 */
	@SaveRequestToken
	@RequestMapping(value = "/editForm")
	public String editForm(WorkLog workLog) {
		Long id = getMe().getId();
		//存入ID								
		WebUtil.getRequest().setAttribute("workLogId", workLog.getWorkLogId());
		WorkLog worklog1 =workLogService.selectWorkLogId(workLog.getWorkLogId());
		WebUtil.getRequest().setAttribute("obj", worklog1);
		//查询用户所在的工程
		List<Project> projectList = workLogService.selectProject(id);
		WebUtil.getRequest().setAttribute("projectList", projectList);
		
		return "admin/workLog-form";
	}
	
	/**
	 * 查询导师
	 * @return 
	 * **/
	@SaveRequestToken
	@RequestMapping(value = "/selectMentor")
	public @ResponseBody AjaxResult selectMentor(){
		AjaxResult result = new AjaxResult();
		
		result.setRows(usersService.selectUsers());
		result.setStatus(AjaxResult.STATUS_OK);
		return result;
	}
	/**
	 * 修改工作日志
	 * @author 吴建
	 * @date 2018/7/23
	 */
	@SaveRequestToken
	@RequestMapping(value = "/addOrModify")
	public @ResponseBody AjaxResult addOrModify(WorkLog workLog){
		int fl=workLogDao.selectToDayWorkLog(workLog);
		if(fl>0){
			return  new AjaxResult(AjaxResult.STATUS_ERR,null,"这个时间段您已为该项目添加了服务日志");
		}
		int flg=workLogService.addOrModify(workLog);
		if(flg>0){
			WorkLog work=workLogService.selectWorkLogId(workLog.getWorkLogId());
			SendWorkLogThread sendWork = new SendWorkLogThread(workLogService,work,Dictionary.BG_COLOR_FINISHED,Dictionary.DINGDING_PUSH_TITLE);
			new Thread(sendWork).start();
			return  new AjaxResult(AjaxResult.STATUS_OK,null,"操作成功");
		}else{
			return  new AjaxResult(AjaxResult.STATUS_ERR,null, "操作失败");
		}
	}
	
	
	/**
	 * 新增工作日志
	 * @author 吴建
	 * @date 2018/7/23
	 */
	@SaveRequestToken
	@RequestMapping(value = "/addWorklog")
	public @ResponseBody AjaxResult addWorklog(WorkLog workLog){
		long flg=workLogService.addWorkLog(workLog);
		if(flg>0){
			return  new AjaxResult(AjaxResult.STATUS_ERR,null,"这个时间段您已为该项目添加了服务日志");
		}
		List<WorkLog> list=workLogService.selectReceiverId(workLog.getSenderId());
		SendWorkLogThread sendWork = new SendWorkLogThread(workLogService,list.get(list.size()-1),Dictionary.BG_COLOR_FINISHED,Dictionary.DINGDING_PUSH_TITLE);
		new Thread(sendWork).start();
		return  new AjaxResult(AjaxResult.STATUS_OK,null,"操作成功");
	}
	
	
	/**
	 * 进入新增工作日志界面
	 * @author 吴建
	 * @date 2018/7/23
	 */
	@SaveRequestToken
	@RequestMapping(value = "/addForm")
	public String addForm(){
		//存入ID								
		Long id = getMe().getId();
		WebUtil.getRequest().setAttribute("senderId", id);
		// 查询人员
		Users userQuery = new Users();
		userQuery.setUserType(Dictionary.USER_TYPE_EMPLOYEE);
		userQuery.setIsDeleted("N");
		List<Users> usersList = usersService.findByModel(userQuery);
		WebUtil.getRequest().setAttribute("usersList", usersList);
		//查询用户所在的项目
		List<Project> projectList =workLogService.selectProject(id);
		WebUtil.getRequest().setAttribute("projectList", projectList);
		return "admin/workLog-addform";
	}
	
	/**
	 * 进入新增工作日志
	 * @author 吴建
	 * @date 2018/7/23
	 */
	@RequestMapping(value = "/summaryGraph")
	public @ResponseBody AjaxResult summaryGraph(String projId){
		AjaxResult result = new AjaxResult();
		//查询项目需要消耗的成本
		List<Map<String,Object>> SummaryGraph =workLogService.selectSummaryGraph(Long.parseLong(projId));
		int num=SummaryGraph.size();
		if(num>0){
		//计算需要消耗的天数
		long day=getDaySub(SummaryGraph.get(0).get("createTime").toString(),SummaryGraph.get(num-1).get("createTime").toString());
		Map map = new HashMap();
		map.put("day", day);
		SummaryGraph.add(map);
		}
		result.putInMap("SummaryGraph", SummaryGraph);
		result.setStatus(AjaxResult.STATUS_OK);
		return result;
	}
	

	/**
     * <li>功能描述：时间相减得到天数
     * @param beginDateStr
     * @param endDateStr
     * @return
     * long 
     * @author 
     */
    public static long getDaySub(String beginDateStr,String endDateStr)
    {
        long day=0;
        java.text.SimpleDateFormat format = new java.text.SimpleDateFormat("yyyy-MM-dd");    
        java.util.Date beginDate;
        java.util.Date endDate;
        try
        {
            beginDate = format.parse(beginDateStr);
            endDate= format.parse(endDateStr);    
            day=(endDate.getTime()-beginDate.getTime())/(24*60*60*1000);    
            //System.out.println("相隔的天数="+day);   
        } catch (ParseException e)
        {
         
            e.printStackTrace();
        }   
        return day;
    }
    
    @RequestMapping("/show")
    public @ResponseBody AjaxResult show(long workLogId) {
    	AjaxResult result = new AjaxResult();
    	WorkLog work = workLogService.selectWorkLogId(workLogId);
    	List<WorkLog> list = new  ArrayList<>();
    	list.add(work);
    	result.setRows(list);
    	result.setStatus(AjaxResult.STATUS_OK);
    	return result;
    }
    
    
    @RequestMapping("/showProject")
    public @ResponseBody AjaxResult showProject() {
    	AjaxResult result = new AjaxResult();
    	Long userId = getMe().getId();
    	List<Project> projectList =workLogService.selectProject(userId);
    	result.setRows(projectList);
    	result.setStatus(AjaxResult.STATUS_OK);
    	return result;
    }
    
    /**
     * 查询所有人的工作日志
     * @author 吴建
     * @return 
     * @date 20181008
     * */
    @RequestMapping("/selectAllUserWork")
    public @ResponseBody AjaxResult selectAllUserWork(WorkLog workLog,PaginationVO pageVo){
    	if (pageVo == null) {
			pageVo = new PaginationVO();
		}
		pageVo.setOrder("desc");
		pageVo.setSort("createTime");
		List<WorkLog> wordList =workLogService.selectAllUserWork(workLog, pageVo);
		LogUtil.info("进入日志列表",null);
		return new AjaxResult(AjaxResult.STATUS_OK, null, null,wordList,workLogService.selectAllUserWorkTotal(workLog));
    }
}
